﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.BusinessLogic;
using System.Web.UI;

namespace Umb.SimpleWebsite.Shared.DataTypes
{
    public class BasePropertyType
    {

        /// <summary>
        /// Register General CSS,JavaScript file for an FiledTypoe in : Prevalue editor, Property editor, Live Editing Editor etc
        /// </summary>
        /// <param name="cname">Css,Javascript file name</param>
        /// <param name="curControl">current control</param>
        public static void AddClientDependsObj(string cname, Control curControl)
        {
            // Adds the client dependencies: don't like script manager it is too complicated
            if (curControl == null) return; 
            cname = string.IsNullOrEmpty(cname) ? curControl.GetType().Name : cname;
            string cssLink = curControl.ResolveClientUrl("/umbraco/css/fieldtypes/" + cname + ".css");
            string jsLink = curControl.ResolveClientUrl("/umbraco/js/fieldtypes/" + cname + ".js");
            List<string> hdrs = new List<string>{
                "<link type=\"text/css\" rel=\"stylesheet\" href=\"" + cssLink+ "\" id=\""+cname+"_autocss\"/>",
                "<script type=\"text/javascript\" src=\"" + jsLink + "\" id=\""+cname+"_autojs\"></script>"
            };
            for (int k = curControl.Page.Header.Controls.Count - 1; k > -1; k--)
            {
                LiteralControl c = curControl.Page.Header.Controls[k] as LiteralControl;
                if (c == null) continue;
                for (int i = hdrs.Count - 1; i > -1; i--)
                {
                    string item = hdrs[i];
                    if (item.Equals(c.Text))
                    {
                        hdrs.Remove(item);
                        break;
                    }
                }
                if (hdrs.Count < 1) break;
            }

            foreach (string item in hdrs)
                curControl.Page.Header.Controls.Add(new LiteralControl(item));
        }
    }
}
